package data

import (
	"blog/model"
	"fmt"

	"crypto/md5"

	"gitee.com/xchengli/blog-lib/database"
)

type UserDataService struct{}

// Login 用户登录
func (s *UserDataService) Login(username, password string) (*model.AdminUser, error) {
	var user model.AdminUser
	db := database.GetDB()

	// 密码加密
	hashedPassword := s.hashPassword(password)

	if err := db.Where("name = ? AND pass = ? AND status >= 0", username, hashedPassword).First(&user).Error; err != nil {
		return nil, err
	}

	return &user, nil
}

// CreateLoginSession 创建登录会话
func (s *UserDataService) CreateLoginSession(user *model.AdminUser, sessionKey, ip, userAgent string) error {
	db := database.GetDB()

	loginRecord := model.AdminLogin{
		Key:       sessionKey,
		UID:       user.ID,
		Status:    1,
		LoginFrom: 1, // Web登录
		LoginIP:   ip,
		UserAgent: userAgent,
	}

	return db.Create(&loginRecord).Error
}

// GetUserBySession 根据会话获取用户信息
func (s *UserDataService) GetUserBySession(sessionKey string) (*model.AdminUser, error) {
	var loginRecord model.AdminLogin
	var user model.AdminUser
	db := database.GetDB()

	// 获取登录记录
	if err := db.Where("key = ? AND status = ?", sessionKey, 1).First(&loginRecord).Error; err != nil {
		return nil, err
	}

	// 获取用户信息
	if err := db.Where("id = ?", loginRecord.UID).First(&user).Error; err != nil {
		return nil, err
	}

	return &user, nil
}

// Logout 用户登出
func (s *UserDataService) Logout(sessionKey string) error {
	db := database.GetDB()
	return db.Model(&model.AdminLogin{}).Where("key = ?", sessionKey).Update("status", 0).Error
}

// CreateUser 创建用户
func (s *UserDataService) CreateUser(user *model.AdminUser) error {
	db := database.GetDB()
	user.Pass = s.hashPassword(user.Pass)
	return db.Create(user).Error
}

// UpdateUser 更新用户
func (s *UserDataService) UpdateUser(user *model.AdminUser) error {
	db := database.GetDB()
	if user.Pass != "" {
		user.Pass = s.hashPassword(user.Pass)
	}
	return db.Save(user).Error
}

// GetUserByID 根据ID获取用户
func (s *UserDataService) GetUserByID(id int64) (*model.AdminUser, error) {
	var user model.AdminUser
	db := database.GetDB()

	if err := db.Where("id = ?", id).First(&user).Error; err != nil {
		return nil, err
	}

	return &user, nil
}

// GetAllUsers 获取所有用户
func (s *UserDataService) GetAllUsers() ([]model.AdminUser, error) {
	var users []model.AdminUser
	db := database.GetDB()

	if err := db.Order("create_time DESC").Find(&users).Error; err != nil {
		return nil, err
	}

	return users, nil
}

// hashPassword 密码加密
func (s *UserDataService) hashPassword(password string) string {
	// 这里可以添加盐值等安全措施
	hash := md5.Sum([]byte(password))
	return fmt.Sprintf("%x", hash)
}
